package com.example.iread.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.viewpager2.widget.ViewPager2;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.iread.R;
import com.example.iread.adapter.ReaderAdapter;
import com.example.iread.bean.ChapterBean;
import com.example.iread.exception.MyException;
import com.example.iread.http.ChapterApi;
import com.example.iread.service.AudioPlayService;
import com.example.iread.util.FloatWindowUtil;
import com.example.iread.util.GsonUtil;
import com.example.iread.util.HttpUtil;
import com.example.iread.util.ToastUtil;
import com.example.iread.util.WaveUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class ReaderActivity extends AppCompatActivity {

    private int chapterId;
    private final String TAG = "SoRiya";

    private boolean isRecording = false;

    private boolean isPlaying = false;

    private final int REQUEST_CODE_RECORD_AUDIO = 0;
    private AudioRecord audioRecord;
    private MediaPlayer mediaPlayer;
    String recordTempDir;
    private ImageButton btn_reader_record, btn_reader_record_play;

//    private final String[] permissions = {
//            Manifest.permission.RECORD_AUDIO
//    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reader);

        recordTempDir = getExternalCacheDir() + File.separator + "record_temp.wav";

        ImageButton btn_reader_close = findViewById(R.id.btn_reader_close);
        btn_reader_close.setOnClickListener(v -> finish());

        chapterId = getIntent().getIntExtra("chapterId", 0);

        loadChapter();

        btn_reader_record = findViewById(R.id.btn_reader_record);
        btn_reader_record.setOnClickListener(v -> {
            if (!isRecording) {
                startRecord();
                ColorStateList colorStateList = ColorStateList.valueOf(getResources().getColor(R.color.danger, getTheme()));
                btn_reader_record.setBackgroundTintList(colorStateList);
            }
            else {
                stopRecord();
                ColorStateList colorStateList = ColorStateList.valueOf(getResources().getColor(R.color.primary, getTheme()));
                btn_reader_record.setBackgroundTintList(colorStateList);
            }
        });

        btn_reader_record_play = findViewById(R.id.btn_reader_record_play);
        btn_reader_record_play.setOnClickListener(v -> {
            if (!isPlaying) {
                isPlaying = true;
                mediaPlayer.start();
                btn_reader_record_play.setImageResource(R.drawable.ic_pause);
            } else {
                isPlaying = false;
                mediaPlayer.pause();
                btn_reader_record_play.setImageResource(R.drawable.ic_play);
            }
        });

    }

    private void startRecord() {
        isRecording = true;
//        Log.i(TAG, "externalCacheDir: " + recordTempDir);

        final int BUFFER_SIZE = AudioRecord.getMinBufferSize(
                16000,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT
        );

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_CODE_RECORD_AUDIO);
            return;
        }
        audioRecord = new AudioRecord(
                MediaRecorder.AudioSource.MIC,
                16000,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                BUFFER_SIZE
        );

        audioRecord.startRecording();

        new Thread(() -> {
            byte[] bytes = new byte[BUFFER_SIZE];

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            try (FileOutputStream fileOutputStream = new FileOutputStream(recordTempDir)) {
                while (isRecording) {
                    audioRecord.read(bytes, 0, BUFFER_SIZE);
                    Log.i(TAG, Arrays.toString(bytes));
                    bos.write(bytes);
                }
                fileOutputStream.write(WaveUtil.getWavHeader(bos.size()).toByteArray());
                fileOutputStream.write(bos.toByteArray());
                fileOutputStream.flush();
                Log.i(TAG, "startRecord: end");
            } catch (IOException e) {
                throw new MyException(500, e.getMessage());
            }

            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(recordTempDir);
                mediaPlayer.prepare();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            new Handler(Looper.getMainLooper()).post(() -> {
                btn_reader_record.setVisibility(View.GONE);
                btn_reader_record_play.setVisibility(View.VISIBLE);
                mediaPlayer.setOnCompletionListener(mp -> {
                    isPlaying = false;
                    btn_reader_record_play.setImageResource(R.drawable.ic_play);
                });
            });
        }).start();
    }

    private void stopRecord() {
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
            isRecording = false;
        }
    }

    private void loadChapter() {
        ViewPager2 vp_reader = findViewById(R.id.vp_reader);

        ImageButton btn_reader_play = findViewById(R.id.btn_reader_play);
        TextView tv_page_num = findViewById(R.id.tv_page_num);

        ChapterApi.getById(chapterId, res -> {
            ChapterBean chapterBean = GsonUtil.parseObject(res.data, ChapterBean.class);
            String content = chapterBean.chapterContent;

            new Handler(Looper.getMainLooper()).post(() -> {
                ReaderAdapter readerAdapter = new ReaderAdapter(this, content);
                vp_reader.setAdapter(readerAdapter);
                vp_reader.setCurrentItem(0);
                vp_reader.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                    }

                    @Override
                    public void onPageSelected(int position) {
                        super.onPageSelected(position);
                        tv_page_num.setText(String.valueOf(position + 1));
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                        super.onPageScrollStateChanged(state);
                    }
                });
                btn_reader_play.setOnClickListener(v -> {
                    if (chapterBean.audio == null || "".equals(chapterBean.audio)) {
                        ToastUtil.show(this, "Resource not uploaded");
                        return;
                    }
                    String url = HttpUtil.getImageUrl(chapterBean.audio);
                    Intent intent = new Intent(this, AudioPlayService.class);
                    intent.putExtra("url", url);
//                    intent.putExtra("chapterName", chapterBean.chapterName);
                    startService(intent);
                    FloatWindowUtil floatWindowUtil = FloatWindowUtil.getInstance();
                    floatWindowUtil.chapterName = chapterBean.chapterName;
                    floatWindowUtil.show(this);
                });
            });
        });

        // 设置动画效果
        vp_reader.setPageTransformer((page, position) -> {
            if (position <= 0) {
                // 当前页左边的页面
                page.setTranslationX(0.0F);
                page.setTranslationY(0.0F);
            } else {
                // 当前页右边的页面
                // 使之堆叠
                page.setTranslationX(page.getWidth() * position * -1);
                page.setTranslationZ(position * -1);
            }
        });
    }

    @Override
    @SuppressWarnings("all")
    protected void onDestroy() {
        super.onDestroy();
        File file = new File(recordTempDir);
        if (file.isFile()) file.delete();

        stopRecord();

        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_RECORD_AUDIO) {
            int grantResult = grantResults[0];
            if (grantResult == PackageManager.PERMISSION_GRANTED)
                startRecord();
            else {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.fromParts("package", getPackageName(), null));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }
}